package itest.stu.cn.ua.dec.att

import org.springframework.transaction.TransactionStatus
import org.springframework.transaction.support.DefaultTransactionDefinition
import org.springframework.transaction.TransactionDefinition
import javax.inject.Inject
import org.springframework.orm.jpa.JpaTransactionManager
import javax.persistence.PersistenceContext
import javax.persistence.EntityManager
import spock.lang.Specification
import org.springframework.test.context.ContextConfiguration
import org.springframework.beans.factory.annotation.Autowired
import stu.cn.ua.dec.att.TestItem

/**
 * author: evgeniy
 * date: 05.02.12
 */
@ContextConfiguration(locations = ["classpath:/webApplicationContext.xml"])
class IntegrationTestUtils extends Specification {

    private Map<String, Stack<TransactionStatus>> activeTransactions = new HashMap<String, Stack<TransactionStatus>>();

    @PersistenceContext
    EntityManager em;

    @Inject
    private TestItem testItem

    def "test smth"(){

        println "started!!!!!!!!!!!!!!"
        def a = 6

//        ApplicationContext context =
//            new ClassPathXmlApplicationContext("/webApplicationContext.xml");

        expect:
//        1==1
//        context.getBean("testItem2").getSmth() == 2
        null != testItem
        null != em

        println "enddddddddd!!!!!!!!!!!!!!"
    }

    /**
     * Starts automatically handled transaction  and attaches it to the current thread
     *
     * @param requireNew defines whether transaction will  have {@link org.springframework.transaction.annotation.Propagation#REQUIRES_NEW} or {@link org.springframework.transaction.annotation.Propagation#REQUIRED}
     * @return true if new transaction was started
     */
    public boolean startTransaction(boolean requireNew = false) {
        boolean transactionStarted = false

        String threadKey = Thread.currentThread().getName();
        Stack<TransactionStatus> transactions = activeTransactions.get(threadKey);  //stack with all transactions initiated by the current thread
        if (null == transactions) {
            transactions = new Stack<TransactionStatus>();
            activeTransactions.put(threadKey, transactions);
            transactionStarted = true
        }
        if (transactions.isEmpty() || requireNew) {
            DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
            transactionDefinition.setPropagationBehavior(requireNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW : TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
            transactions.push(status);
            transactionStarted = true
        }

        transactionStarted
    }
}
